<!-- 报文查询-->

<template>
    <!-- 报表检索条件组件 -->
    <ReportSearch :loading="loading" :searchFormDatas="searchFormDatas" v-model:searchForm="searchForm"
        @handleSearchForm="handleSearchForm" @handleResetForm="handleResetForm">
        <span v-show="chartShow" class="searchBtn">图表</span>
        <span class="searchBtn" @click="handleSetup"><i class="iconfont icon-shezhi1 icon-setup"></i>设置</span>
    </ReportSearch>
    <!-- 报表表格标题组件-->
    <ReportTableTitle :tableTitle="tableTitle" />
    <!-- 报表表格组件-->
    <ReportTable :loading="loading" :tableData="tableData" :pageInfo="pageInfo" :summaryData="summaryData"
        :tableColumnData="tableColumnData" :tableColumnWidthData="tableColumnWidthData">
        <el-table-column :resizable="false" label="操作" width="50">
			<template #default="scope">
				<a class="cF5A mr10" @click="handleSee(scope.row)"> 查看 </a>
			</template>
		</el-table-column>
    </ReportTable>
    <!-- 报表表格分页组件-->
    <ReportTablePage v-model:pageInfo="pageInfo" @handleSearchForm="handleSearchForm" />
    <template v-if="dialogVisible">
        <el-dialog v-model="dialogVisible" title="信息" width="800" :close-on-click-modal="false">
            <Transfer :selectedIds="selectedIds" @closeDialog="closeDialog" @restore="restore"/>
        </el-dialog>
    </template>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';

import ReportSearch from '@/components/reportSearch/index.vue';
import ReportTableTitle from '@/components/reportTableTitle/index.vue';
import ReportTable from '@/components/reportTable/index.vue';
import ReportTablePage from '@/components/reportTablePage/index.vue';
import Transfer from '@/components/elements/Transfer.vue';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/technicalDataAnalysis';
import * as basicServer from '@/api/modules/common';

import { getYesterday, getCurTime } from '@/utils/date';
import { apiFn, deepCopy } from '@/utils/utilFns';

// 报表表格标题
const defaultTitle = '报文查询';
const tableTitle = ref(defaultTitle);

// 默认表单数据
const defaultSearchForm = {
    orgIds: local.getItem('defaultOrgIds'),
    timeFrame: [`${getYesterday(0)} 00:00:00`, getCurTime()],
    vehicleNumber: '',
    type: '02',
    sample: '1'
};

const dialogVisible = ref(false);

// 默认分页数据
const defaultPageInfo = {
    currentPage: 1,
    pageSize: 20,
    total: 0
};

const chartConfigData = ref({});

// 加载状态
const loading = ref(false);
const field = ref('');
const selectedIds = ref([]);

// 默认表头
const defaultTableColumnData = [
    {
        prop: 'vehicleNo',
        label: '车辆编号'
    }, {
        prop: 'vin',
        label: 'VIN'
    }, {
        prop: 'msgType',
        label: '报文类型'
    }, {
        prop: 'sys_time',
        label: '平台接收时间'
    }, {
        prop: 'collect_time',
        label: '数据采集时间'
    }
];

// 表头数据
const tableColumnData = ref([]);

// 表格数据
const tableData = ref([]);

// 表头宽度数据
const tableColumnWidthData = ref({});

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'selectTree',
        label: '所属组织',
        prop: 'orgIds',
        options: [],
        api: () => { },
        placeholder: '请选择所属组织',
        rules: [{ required: true, message: '请选择所属组织', trigger: ['blur, change'] }]
    },
    {
        id: 1,
        type: 'dateTimeRangePicker',
        prop: 'timeFrame',
        label: '时间范围',
        options: [],
        api: () => { },
        placeholder: '请选择时间范围',
        rules: [{ required: true, message: '请选择时间范围', trigger: ['change'] }]
    },
    {
        id: 2,
        type: 'select',
        prop: 'type',
        label: '报文类型',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 3,
        type: 'select',
        prop: 'sample',
        label: '按秒采样',
        options: [{ name: 1, value: '1' }, { name: 2, value: '2' }, { name: 3, value: '3' }, { name: 4, value: '4' }, { name: 5, value: '5' }],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 4,
        type: 'select',
        prop: 'vehicleNumber',
        label: '车辆编号',
        options: [],
        api: () => { },
        placeholder: '请选择',
        rules: [{ required: true, message: '请选择', trigger: ['change'] }]
    }
]);

// 表单数据
const searchForm = reactive(deepCopy(defaultSearchForm));

// 分页数据
const pageInfo = reactive(deepCopy(defaultPageInfo));

// 汇总数据
const summaryData = ref({});

const chartShow = computed(() => {
    return Object.keys(chartConfigData.value).length > 0; 
});

onMounted(() => {
    getMessageTypeOptions();
    getEquipNumberOptions();
    getUserCustomColumn();
    getTableTitle();
});

// 所属组织变化监听
watch(() => searchForm.orgIds, () => {
    searchForm.vehicleNumber = '';
    getEquipNumberOptions();
});

// 设置
const handleSetup = () => {
    dialogVisible.value = true;
};

// 关闭用户配置弹框
const closeDialog = () => {
    dialogVisible.value = false;
};

// 恢复
const restore = () => {
    dialogVisible.value = false;
    getUserCustomColumn();
};

// 获取表格标题
const getTableTitle = () => {
    const { timeFrame } = searchForm;
    tableTitle.value = `报文查询 ( ${timeFrame[0]} ~ ${timeFrame[1]}})`;
};

// 获取用户自定义配置列
const getUserCustomColumn = () => {
    const params = {
        equal: { userId: local.getUser().id, type: '1', }
    };

    apiFn(server.getUserCustomColumn, params)
        .then((res) => {
            const { code, data = [] } = res;
            let codes = [];
            const ids = [];
            if (code === '200') {
                const generateData = data.map(item => {
                    const { id, columnName, columnCode } = item;
                    ids.push(id);
                    codes.push(columnCode);
                    
                    return {
                        prop: columnCode,
                        label: columnName
                    };
                });
                selectedIds.value = ids;
                tableColumnData.value = [...defaultTableColumnData, ...generateData];
                field.value = codes.join(',');
                getTableColumnWidth();
            }
        }).catch(() => {
            tableColumnData.vlaue = [];
        });
};

// 获取表头宽度
const getTableColumnWidth = () => {
    let labelWidth = {};
    const datas = tableColumnData.value;
    
    datas.forEach(data => {
        const { prop, label } = data;
        const length = label.length;
        if(length * 15 < 80){
            labelWidth[prop] = 80;
        }else{
            labelWidth[prop] = length * 15;
        }
    });
    
    tableColumnWidthData.value = labelWidth;
};

// 获取报文类型
const getMessageTypeOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_message_type' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[2]['options'] = data;
            }
        }).catch(() => {
            searchFormDatas.value[2]['options'] = [];
        });
};

// 获取设备编号
const getEquipNumberOptions = () => {
    let params = {
        like: { orgId: searchForm.orgIds },
        equal: { vehicleCategory: '1, 2' }
    };

    apiFn(basicServer.getNumberList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[4]['options'] = data
            }
        }).catch(() => {
            searchFormDatas.value[4]['options'] = [];
        });
};

// 获取查询参数
const getParams = () => {
    const { orgIds, timeFrame, vehicleNumber, sample, type } = searchForm;
    const { pageSize, currentPage } = pageInfo;

    const vehicleNo = getVehicleNo(vehicleNumber);

    const params = {
        equal: {
            startTime: timeFrame[0],
            endTime: timeFrame[1],
            field: field.value,
            orgId: orgIds,
            sample,
            type,
            vehicleNo,
            vehicleVin: vehicleNumber
        },
        limit: pageSize,
        page: currentPage,
    };

    return params;
};

// 获取车辆编号
const getVehicleNo = (vin) => {
    const options = searchFormDatas.value[4]['options'];

    const target = options.find(item => item.value === vin);

    const vehicleNo = target ? target.name : '';

    return vehicleNo;
};

// 获取报表列表内容
const getTableList = () => {
    const params = getParams();
    loading.value = true;
    apiFn(server.getMessageTableList, params)
        .then(res => {
            const { code, data, recordsTotal } = res;
            if (code === '200') {
                if (data.length > 0) {
                    tableData.value = data;
                } else {
                    tableData.value = [];
                }

                pageInfo.total = recordsTotal;
            }
        }).catch(() => {
            tableData.value = [];
            pageInfo.total = 0;
        }).finally(() => {
            loading.value = false;
        })
};

// 查询
const handleSearchForm = (type) => {
    if (loading.value) return;

    if (type === 'search') {
        Object.keys(defaultPageInfo).forEach(key => {
            if (key in pageInfo) {
                pageInfo[key] = defaultPageInfo[key];
            }
        })
    }
    
    getTableTitle();
    getTableList();
};

// 导出
const handleExport = (cb) => {
    if (!tableData.value.length) {
        ElMessage.warning('无查询数据导出!');
        return;
    }

    const equal = getParams().equal;
    const { startDate, endDate, vin, orgId } = equal;

    const params = {
        equal: {
            ...equal,
            createUser: local.getUser().id,
            exportStartTime: startDate,
            exportEndTime: endDate
        }
    };

    apiFn(server.addMessageExportTask, params)
        .then(res => {
            const { code } = res;
            if (code === '200') {
                cb && cb({ orgId, vin });
                ElMessage.success('添加成功!');
            }
        }).catch(() => {
            ElMessage.error('导出报文添加失败!');
        })

};

// 重置
const handleResetForm = () => {
    Object.keys(searchForm).forEach(key => {
        if (key in defaultSearchForm) {
            searchForm[key] = defaultSearchForm[key];
        }
    });

    Object.keys(defaultPageInfo).forEach(key => {
        if (key in pageInfo) {
            pageInfo[key] = defaultPageInfo[key];
        }
    });

    // getDefaultTime();

    tableTitle.value = defaultTitle;
    tableColumnData.value = [];
    tableData.value = [];
};

defineExpose({ handleExport });
</script>

<style lang="scss" scoped></style>